package com.googlecode.animator.controller.mediators
{
	import com.googlecode.animator.data.Notifications;
	import com.googlecode.animator.data.materials.MovieMaterialVO;
	import com.googlecode.animator.data.objects3d.CubeVO;
	import com.googlecode.animator.data.objects3d.PlaneVO;
	import com.googlecode.animator.data.objects3d.SphereVO;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	import mx.controls.SWFLoader;
	
	import org.puremvc.as3.patterns.mediator.Mediator;

	public class SWFLoaderMediator extends Mediator
	{
		/**
		 * Name prefix used to create dynamic mediator names.
		 * Names will be appended by the INSTANCE_COUNT to create a unique mediator name. 
		 */
		protected static const NAME_PREFIX:String = "SWFLoaderMediator_";
		
		/**
		 * Counter indicating how many instances of this class have been created. 
		 */		
		protected static var INSTANCE_COUNT:uint = 0;
		
		private var _loader:SWFLoader = new SWFLoader();
		private var _object3D:*;
		
		public function SWFLoaderMediator(object3D:*)
		{
			super(NAME_PREFIX + INSTANCE_COUNT);
			
			_object3D = object3D;
			
			// update instance count so we obtain a unique name for each Mediator instance
			INSTANCE_COUNT++;
		}
		
		override public function onRegister():void
		{	
			var mat:MovieMaterialVO;
			
			if(_object3D is PlaneVO)
			{
				mat = (_object3D as PlaneVO).material as MovieMaterialVO;
			}
			
			if(_object3D is CubeVO)
			{
				mat = (_object3D as CubeVO).materialsList[(_object3D as CubeVO).selectedFace];
			}
			
			if(_object3D is SphereVO)
			{
				mat = (_object3D as SphereVO).material as MovieMaterialVO;
			}
trace("WWWWWWWWWWWWWWWW", _object3D);
			_loader.addEventListener(Event.COMPLETE, onSWFComplete);
			_loader.load(mat.filePath); 
		}
		
		override public function onRemove():void
		{
			_loader.removeEventListener(Event.COMPLETE, onSWFComplete);
		}
		
		protected function onSWFComplete(evt:Event):void
		{	
			var swf:DisplayObject = (evt.target as SWFLoader).content;
			var mat:MovieMaterialVO;
			
			if(_object3D is PlaneVO)
			{
				mat = (_object3D as PlaneVO).material.clone() as MovieMaterialVO;
				(_object3D as PlaneVO).material = mat;
			}
			
			if(_object3D is CubeVO)
			{
				mat = (_object3D as CubeVO).materialsList[(_object3D as CubeVO).selectedFace].clone() as MovieMaterialVO;
				(_object3D as CubeVO).materialsList[(_object3D as CubeVO).selectedFace] = mat;
				
			}
			
			if(_object3D is SphereVO)
			{
				mat = (_object3D as SphereVO).material.clone() as MovieMaterialVO;
				(_object3D as SphereVO).material = mat;
			}

			mat.swf = swf;

	
			sendNotification(Notifications.OBJECT3D_SWF_LOADED, _object3D); 
			// we can't guarantee that the Mediator instance was registered
			if(facade)
			{
				facade.removeMediator(getMediatorName());
			}
				
		}
	}
}